package com.example.heimaplayer.ui.fragment

import android.graphics.Color
import android.util.Log
import android.view.Gravity
import android.view.View
import android.webkit.WebSettings
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.heimaplayer.R
import com.example.heimaplayer.adapter.HomeAdapter
import com.example.heimaplayer.application.MyApplication
import com.example.heimaplayer.base.BaseFragment
import com.example.heimaplayer.model.HomeBean
import com.example.heimaplayer.util.ThreadUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kotlin.musicplayer.utils.URLProviderUtils
import kotlinx.android.synthetic.main.activity_home.*
import okhttp3.*
import org.jetbrains.anko.support.v4.toast
import java.io.IOException

class HomeFragment:BaseFragment() {
    //调用数据

    private lateinit var adapter: HomeAdapter
//    val adapter by lazy { HomeAdapter() }
    override fun initView(): View? {
        return View.inflate(context, R.layout.fragment_home,null)
    }
//

    override fun initListener() {
        super.initListener()
        adapter = HomeAdapter()
//        初始化recvlcleview
//    是不是很神奇，居然木有findViewById直接就可以用recyclerView这个对象。
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.adapter = adapter
        recycler_view.addOnScrollListener(object :RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //是否是最后一条显示
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager){
                    //由于recycleView 还有其他样式列表 所以这里只有下拉列表类型才能处理分页
                    val manager = layoutManager
                    val lastPosition = manager.findLastVisibleItemPosition()
                    if (lastPosition == adapter.itemCount -1){
                        loadMoreDatas(adapter.itemCount-1)
                    }
                }
            }
        })




        lay_refresh.setColorSchemeColors(Color.RED,Color.YELLOW,Color.BLUE)
        //下拉刷新
        lay_refresh.setOnRefreshListener { loadDayas() }
    }

    private fun loadMoreDatas(offiset: Int) {
        val path = URLProviderUtils.getHomeUrl(0,5)
        val client = OkHttpClient()
        val request = Request.Builder()
            .get()
            .url(path)
            .addHeader("User-Agent",WebSettings.getDefaultUserAgent(MyApplication.instance))
            .build()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                toast("数据获取出错")
                ThreadUtil.runOnMainThread(object:Runnable{
                    override fun run() {
                        lay_refresh.isRefreshing =false

                    }
                })
//                println("数据获取出错")
//                myToast("数据获取出错"+Thread.currentThread().name)
//                Log.d("数据获取出错", Thread.currentThread().name)
//                print("数据获取出错"+Thread.currentThread().name)
            }
            override fun onResponse(call: Call, response: Response) {
                val result = response?.body?.string()
                val gson = Gson()
                val list = gson.fromJson<HomeBean>(
                    result,
                    object : TypeToken<HomeBean>() {}.type
                )
                myToast("数据获取成功")

                ThreadUtil.runOnMainThread(object : Runnable {
                    override fun run() {
//                        println(list.songlist)
                        lay_refresh.isRefreshing = false
                        adapter?.loadMoreData(list.songlist)
//                        adapter?.notifyDataSetChanged()
                    }
                })
            }
        })
    }

    //
    override fun initData() {
        //初始化数据
        super.initData()
        loadDayas()

    }

    private fun loadDayas() {
        val path = URLProviderUtils.getHomeUrl(0,5)
        val client = OkHttpClient()
        val request = Request.Builder()
            .get()
            .url(path)
            .addHeader("User-Agent",WebSettings.getDefaultUserAgent(MyApplication.instance))
            .build()
        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                toast("数据获取出错")
                ThreadUtil.runOnMainThread(object:Runnable{
                    override fun run() {
                        lay_refresh.isRefreshing =false

                    }
                })
//                println("数据获取出错")
//                myToast("数据获取出错"+Thread.currentThread().name)
//                Log.d("数据获取出错", Thread.currentThread().name)
//                print("数据获取出错"+Thread.currentThread().name)
            }
            override fun onResponse(call: Call, response: Response) {
                val result = response?.body?.string()
                val gson = Gson()
                val list = gson.fromJson<HomeBean>(
                    result,
                    object : TypeToken<HomeBean>() {}.type
                )
                myToast("数据获取成功")

                ThreadUtil.runOnMainThread(object : Runnable {
                    override fun run() {
//                        println(list.songlist)
                        lay_refresh.isRefreshing = false
                        adapter?.setData(list.songlist)
//                        adapter?.notifyDataSetChanged()
                    }
                })
            }
        })
    }

}